import { toast } from 'sard-uniapp'
import { getUserInfoApi, loginWechatMiniProgramApi, logOutApi } from '@/api'
import { EAuthType } from '@/api/types'
import { useAuthStore } from '../authStore/authStore'
import { useUserStore } from '../userStore/userStore'

export function authModule() {
  // 获取微信登录code
  const getWxCode = () => {
    return new Promise<UniApp.LoginRes>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: res => resolve(res),
        fail: err => reject(new Error(err.errMsg || JSON.stringify(err))),
      })
    })
  }
  // 获取用户信息
  const getUserInfo = async () => {
    const res = await getUserInfoApi()
    useUserStore().setUserInfo(res)
  }
  // 微信一键登录
  const wxLogin = async () => {
    try {
      const code = await getWxCode()
      console.log('微信登录获取到的code：', code)
      
      // 微信小程序登录，不需要获取用户信息，直接使用 code 登录
      const res = await loginWechatMiniProgramApi({
        code: code.code,
        authType: EAuthType.Wechat_Mini_Program,
        clientId: import.meta.env.VITE_CLIENT_ID,
      })
      console.log('微信登录返回信息：', res)
      useAuthStore().setToken(res.token)
      await getUserInfo()
      toast.success('登录成功')
    } catch (error) {
       console.error('微信登录失败：', error)
       toast.fail(`登录失败：${error.message || '未知错误'}`)
       throw error
     }
  }

  // 用户登出
  const logout = async (): Promise<void> => {
    // TODO: 实现登出逻辑
    await logOutApi()
    useAuthStore().resetToken()
    useUserStore().clearUserInfo()
    toast.success('登出成功')
  }

  // 导出方法
  return {
    wxLogin,
    logout,
    getUserInfo,
  }
}
